


const getSource = (source, type) => {
    const regex = new RegExp(`<${type}[^>]*>`)
    let openingTag = source.match(regex)

    if (!openingTag) {
        return ''
    } else {
        openingTag = openingTag[0]
    }

    return source.slice(source.indexOf(openingTag) + openingTag.length, source.lastIndexOf(`</${type}>`))
}
import { useStyleTag ,tryOnBeforeUnmount} from '@vueuse/core'
export default (key,codeStr) => {
    let script = getSource(codeStr, 'script').replace(/export default/, 'return ')
    let css = getSource(codeStr, 'style')
    let template = getSource(codeStr, 'template')

    if (css) {
        let scopedCss = []
        let cssNames = css.match(/(\.[a-zA-Z0-9\-_:\s]*?)\{/sg)
        if(cssNames){
            cssNames.forEach(cssName=>{
                cssName = cssName.replace(/\s/,'').replace('{','').replace('.','').trim()
                let reg1 = new RegExp("(class=[\"']"+cssName+"[\"'])",'g')
                let reg2 = new RegExp("(class=[\"']\s"+cssName+"[\"'])",'g')
                scopedCss.push(cssName)
                template = template.replace(reg1,"$1 data-v-"+key)
                template = template.replace(reg2,"$1 data-v-"+key)
            })
            css = css.replace(/\.([a-zA-Z0-9\-_].*?)\{.*?\}/sg,function (a,b){
                if(scopedCss.indexOf(b) > -1){

                    return a.replace(b,b.trim()+"[data-v-"+key+"]")
                }
                return a.trim()
            })
        }


    }
    let component = {
        ...new Function(script)(), template
    }
    component.beforeCreate = function () {
         const {unload} = useStyleTag(css)
         tryOnBeforeUnmount(unload)
    }
    return component
}
